package com.wt.admin.controller.ai;


import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.util.LocalUtil;
import com.wt.admin.domain.dto.ai.AgentsInfoDTO;
import com.wt.admin.domain.dto.ai.ChatDTO;
import com.wt.admin.domain.dto.ai.ChatModelContentDTO;
import com.wt.admin.domain.vo.ai.*;
import com.wt.admin.domain.vo.sys.UserVO;
import com.wt.admin.service.ai.ChatProxyService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import java.util.List;


@RestController
@RequestMapping("chat")
public class ChatController {

    @Resource
    private ChatProxyService chatProxyService;


    @PostMapping("agentsList")
    public Rep<List<AgentsInfoVO>> agentsList(@RequestBody AgentsInfoDTO data) {
        return Rep.ok(chatProxyService.agentsList(data));
    }

    @PostMapping("modeContentList")
    public Rep<List<ChatModelContentVO>> modeContentList(@RequestBody ChatModelContentDTO data) {
        return Rep.ok(chatProxyService.getChatModelContentService().modeContentList(data, LocalUtil.getUser()));
    }

    @PostMapping("modeContentDel")
    public Rep<ChatModelContentVO> modeContentDel(@RequestBody ChatModelContentDTO data) {
        return Rep.ok(chatProxyService.modeContentDel(data));
    }

    @PostMapping("modeContentEdit")
    public Rep<ChatModelContentVO> modeContentEdit(@RequestBody ChatDTO data) {
        return Rep.ok(chatProxyService.modeContentEdit(data,LocalUtil.getUser()));
    }

    @PostMapping("modeContentInfo")
    public Rep<ChatModelContentVO> modeContentInfo(@RequestBody ChatModelContentDTO data) {
        return Rep.ok(chatProxyService.modeContentInfo(data, LocalUtil.getUser()));
    }

    @PostMapping("question")
    public Flux<String> question(@RequestBody ChatDTO data) {
        UserVO user = LocalUtil.getUser();
        if(data.getChatConfig().getEnableMCP()){
            String content = chatProxyService.question(data, user)
                    .call()
                    .content();
            chatProxyService.reply(content,data,user);
            return Flux.just(content);
        }
        final StringBuilder msg = new StringBuilder();
        return chatProxyService.question(data,user)
                .stream()
                .content()
                .doOnNext(msg::append)
                .onErrorResume(error -> Flux.just(error.getMessage()))
                .doFinally((signalType) -> {
                    chatProxyService.reply(msg.toString(),data,user);
                    msg.setLength(0);
                });
    }


}
